package com.tensquare.spit.controller;

import com.tensquare.spit.pojo.Spit;
import com.tensquare.spit.service.SpitService;
import entity.PageResult;
import entity.Result;
import entity.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

/**
 * @Auther: hjk
 * @Date: 2019/6/20 00:41
 * @Description:
 */
@RestController
@CrossOrigin
@RequestMapping("/spit")
public class SpitController {

    @Autowired
    private SpitService spitService;

    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping
    public Result findAll(){
        return new Result(true, StatusCode.OK,"查询成功",spitService.findAll());
    }

    @GetMapping("/{spitId}")
    public Result findById(@PathVariable String spitId){
        return new Result(true, StatusCode.OK,"查询成功",spitService.findById(spitId));
    }

    @PostMapping()
    public Result save(@RequestBody Spit spit){
        spitService.save(spit);
        return new Result(true, StatusCode.OK,"保存成功");
    }

    @PutMapping("/{spitId}")
    public Result update(@PathVariable String spitId,@RequestBody Spit spit){
        spit.set_id(spitId);
        spitService.save(spit);
        return new Result(true, StatusCode.OK,"修改成功");
    }

    @DeleteMapping("/{spitId}")
    public Result deleteById(@PathVariable String spitId){
        spitService.deleteById(spitId);
        return new Result(true, StatusCode.OK,"删除成功");
    }

    @GetMapping("/comment/{parentId}/{page}/{size}")
    public Result findByParentId(@PathVariable String parentId,@PathVariable int page,@PathVariable int size){
        Page<Spit> spitPage = spitService.findByParentId(parentId, page, size);
        return new Result(true, StatusCode.OK,"删除成功",new PageResult<Spit>(spitPage.getTotalElements(),spitPage.getContent()));
    }

    /**
     * 吐槽点赞
     * @param spitId
     * @param spitId
     * @return
     */
    @PutMapping("/thumbup/{spitId}")
    public Result thumbup(@PathVariable String spitId){
        //判断当前用户是否已经点赞，暂时没有登录，userId写死
        String userId = "123";
        if(redisTemplate.opsForValue().get("thumbup_" + userId) != null){
            new Result(false, StatusCode.REMOTEERROR,"不能重复点赞");
        }
        spitService.thumbup(spitId);
        //点赞成功后记录以点赞
        redisTemplate.opsForValue().set("thumbup_" + userId,1);
        return new Result(true, StatusCode.OK,"点赞成功");
    }
}
